import 'dart:async';
import 'dart:io';
import 'dart:math' as math;

import 'package:cunyutech_flutter_ui/cunyutech_flutter_ui.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:package_info/package_info.dart';

import 'LogConsole.dart';
import 'WebApiConsole.dart';

class TestAction extends StatefulWidget {
  TestAction({ Key key, this.content, this.isDev = false }) : super(key: key);

  final Widget content;
  final bool isDev;
  static EventBus eventBus = EventBus();

  @override
  _TestActionState createState() => _TestActionState();
}

class _TestActionState extends State<TestAction> {
  //设定Widget的偏移量
  double dragWidth = 60;
  Offset offset = Offset(100, kToolbarHeight + 100);
  PackageInfo packageInfo;
  bool hiddenTag = false;
  /// 打印日志
  bool printLog = false;
  /// 打印Api日志
  bool printRequestLog = false;

  StreamSubscription<bool> subscription;

  @override
  void initState() {
    initData();
    super.initState();
  }

  @override
  void dispose() { 
    if(subscription != null) {
      subscription.cancel();
    }
    super.dispose();
  }

  void initData() async {
    if(widget.isDev != true) {
      hiddenTag = true;
    }
    
    packageInfo = await PackageInfo.fromPlatform();
    subscription = TestAction.eventBus.on<bool>().listen((bool hidden){
      setState(() {
        hiddenTag = hidden;
      });
    });
  }

  handleClose() async {
    int index = await showSystemAlert(
      rootContext: context,
      title: "确定要关闭该浮动按钮",
      actions: [
        SystemAlertAction("取消"),
        SystemAlertAction("确定"),
      ],
    );
    if(index == 1) {
      hiddenTag = true;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    var cs = CYThemeData.of(context);
    if(hiddenTag) {
      return widget.content;
    }
    return Stack(
      children: <Widget>[
        widget.content,
        Positioned(
          child: printLog == true ? LogConsole() : Container(),
          left: offset.dx+(dragWidth * math.pi / 4) - 10,
          top: offset.dy+(dragWidth * math.pi / 4) - 20,
        ),
        Positioned(
          child: printRequestLog == true ? WebApiConsole() : Container(),
          left: offset.dx+(dragWidth * math.pi / 4) - 10,
          top: offset.dy+(dragWidth * math.pi / 4) - 20,
        ),
        Positioned(
          left: offset.dx,
          top: offset.dy,
          child: GestureDetector(
            //更新child的位置
            onPanUpdate: (details) {
              offset += details.delta;
              setState(() {});
            },
            //拖动结束，处理child贴边悬浮
            onPanEnd: (details) {

            },
            onLongPress: () async {
              int index = await showBSActionDialog(
                context,
                [
                  PrimaryButtonProps(
                     
                    title: "关闭浮动按钮"
                  ),
                  PrimaryButtonProps(
                     
                    title: "切换日志打印"
                  ),
                  PrimaryButtonProps(
                     
                    title: "切换接口打印"
                  ),
                  PrimaryButtonProps(
                     
                    title: "设置代理"
                  )
                ]
              );

              if(index == 0) handleClose();
              if(index == 1) {
                setState(() {
                  printLog = !printLog;
                });
              }
              if(index == 2) {
                setState(() {
                  printRequestLog = !printRequestLog;
                });
              }
              if(index == 3) {
                Navigator.of(context).pushNamed("proxy_settings");
              }
            },
            onTap: (){
              showSystemAlert(
                rootContext: context,
                title: "版本信息：${packageInfo?.version}\n操作系统：${Platform.operatingSystemVersion}\n",
                actions: [
                  SystemAlertAction("确定",)
                ]
              );
            },
            //悬浮部件布局
            child: Container(
              width: dragWidth,
              height: dragWidth,
              decoration: BoxDecoration(
                color: cs.primaryColor,
                borderRadius: BorderRadius.circular(dragWidth / 2),
              ),
              child: CYTitle("测试", color: cs.darkForeColorSystem.primaryColor, alignment: Alignment.center),
            )
          ),
        )
      ],
    );
  }
}

